package jsyf.oa.service.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.business.*;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wreport.WReportCustomerDao;
import jsyf.oa.entity.business.*;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.entity.wreport.WReportCustomerEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import jsyf.com.util.DateUtils;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.facade.business.BusinessFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;
import static jsyf.oa.dao.wechat.service_company.TokenDao.PushTemplate.BUSINESS_AUDIT_NOTIFY;

@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class BusinessService implements BusinessFacade {
    @Autowired
    private BusinessMainDao businessMainDao;
    @Autowired
    private BusinessAuditDao businessAuditDao;
    @Autowired
    private BusinessCopierDao businessCopierDao;
    @Autowired
    private BusinessTrustTrialDao businessTrustTrialDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private WReportCustomerDao wReportCustomerDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private BusinessReceiverDao receiverDao;

    @Override
    public String save(String jsonData) {
        BusinessEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), BusinessEntity.class);
        Integer rows;
        //第一步，保存主表信息
        BusinessMainEntity entity = model.getMain();
        //保存客户信息：添加&修改
        WReportCustomerEntity oldWReportCustomerEntity = wReportCustomerDao.getByTel(entity.getCustomerTel());
        if (oldWReportCustomerEntity == null) {
            WReportCustomerEntity wReportCustomerEntity = new WReportCustomerEntity();
            wReportCustomerEntity.setName(entity.getCustomerName());
            wReportCustomerEntity.setTel(entity.getCustomerTel());
            wReportCustomerEntity.setCustomerCredit(entity.getCustomerCredit());
            wReportCustomerEntity.setExistingDevice(entity.getExistingDevice());
            wReportCustomerEntity.setCompetitorCondition(entity.getCompetitorCondition());
            wReportCustomerEntity.setOtherCondition(entity.getOtherCondition());
            wReportCustomerEntity.setCreateUserId(entity.getCreateUserId());
            wReportCustomerDao.add(wReportCustomerEntity);
            entity.setCustomerId(wReportCustomerEntity.getId());
        }
        /*else {
            oldWReportCustomerEntity.setOtherCondition(entity.getOtherCondition());
            oldWReportCustomerEntity.setCustomerCredit(entity.getCustomerCredit());
            oldWReportCustomerEntity.setExistingDevice(entity.getExistingDevice());
            oldWReportCustomerEntity.setCompetitorCondition(entity.getCompetitorCondition());
            wReportCustomerDao.update(oldWReportCustomerEntity);
        }*/
        if (entity.getModelName() != null) {
            entity.setModelName(entity.getModelName().toUpperCase());
        }
        if (entity.getAuditFlag() == 0) {
            //如果是提交申请，则设置当前审核人信息
            BusinessAuditEntity firstAuditor = model.getAuditors().get(0);
            entity.setCurrentAuditorId(firstAuditor.getAuditorId());
            String[] arrAuditorName = firstAuditor.getAuditorName().split("-");
            entity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
            //企业号:给第一审核人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", firstAuditor.getAuditorId());
            msgObject.put("content", String.format(BUSINESS_AUDIT_AUDIT,
                    firstAuditor.getAuditorName(),
                    entity.getModelName(),
                    entity.getDealPrice(),
                    entity.getCreateUserName(),
                    DateUtils.parse(businessMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            //推送: 给第一审核人推送红点提示
            tokenDao.sendJPushMsg(firstAuditor.getAuditorId(), String.format(BUSINESS_AUDIT_NOTIFY, entity.getCreateUserName()));
        }
        if (StringUtils.isBlank(entity.getId()) || "0".equals(entity.getId())) {
            //新建
            rows = businessMainDao.add(entity);
        } else {
            BusinessMainEntity businessMainEntity = (BusinessMainEntity) businessMainDao.getIBaseEntityById(entity.getId());
            businessMainEntity.setCustomerId(entity.getCustomerId());
            businessMainEntity.setDealModelId(entity.getDealModelId());
            businessMainEntity.setBrandId(entity.getBrandId());
            businessMainEntity.setBrandName(entity.getBrandName());
            businessMainEntity.setModelName(entity.getModelName());
            businessMainEntity.setDealPrice(entity.getDealPrice());
            businessMainEntity.setDealNumber(entity.getDealNumber());
            businessMainEntity.setDealTime(entity.getDealTime());
            businessMainEntity.setDealMoney(entity.getDealMoney());
            businessMainEntity.setAuditFlag(entity.getAuditFlag());
            businessMainEntity.setCurrentAuditorId(entity.getCurrentAuditorId());
            businessMainEntity.setCurrentAuditorName(entity.getCurrentAuditorName());
            businessMainEntity.setCopierReturnReason(entity.getCopierReturnReason());
            businessMainEntity.setBuyType(entity.getBuyType());
            businessMainEntity.setPayMoney(entity.getPayMoney());
            businessMainEntity.setStageLimit(entity.getStageLimit());
            businessMainEntity.setLoanMoney(entity.getLoanMoney());
            businessMainEntity.setFinancingCompany(entity.getFinancingCompany());
            businessMainEntity.setPayRatio(entity.getPayRatio());
            businessMainEntity.setDisplaceFlag(entity.getDisplaceFlag());
            businessMainEntity.setProOldModel(entity.getProOldModel());
            businessMainEntity.setProOldName(entity.getProOldName());
            businessMainEntity.setProOldAssessment(entity.getProOldAssessment());
            businessMainEntity.setProOldReplacement(entity.getProOldReplacement());
            businessMainEntity.setProOldAllowance(entity.getProOldAllowance());
            businessMainEntity.setPartGift(entity.getPartGift());
            businessMainEntity.setFreightFee(entity.getFreightFee());
            businessMainEntity.setLaborFee(entity.getLaborFee());
            businessMainEntity.setOtherPrice(entity.getOtherPrice());
            businessMainEntity.setDealNetPrice(entity.getDealNetPrice());
            businessMainEntity.setLimitPrice(entity.getLimitPrice());
            businessMainEntity.setDelFlag(entity.getDelFlag());
            businessMainEntity.setTrustTrialFlag(entity.getTrustTrialFlag());
            businessMainEntity.setTrustTrialId(entity.getTrustTrialId());
            businessMainEntity.setTrustTrialName(entity.getTrustTrialName());
            businessMainEntity.setTrustTrialReason(entity.getTrustTrialReason());
            businessMainEntity.setValveFlag(entity.getValveFlag());
            businessMainEntity.setPipelineFlag(entity.getPipelineFlag());
            businessMainEntity.setReplacementDesc(entity.getReplacementDesc());
            businessMainEntity.setPaymentDesc(entity.getPaymentDesc());
            businessMainEntity.setDealDesc(entity.getDealDesc());
            businessMainEntity.setPartGiftDesc(entity.getPartGiftDesc());
            businessMainEntity.setRegionManagerId(entity.getRegionManagerId());
            businessMainEntity.setRegionManagerName(entity.getRegionManagerName());
            businessMainEntity.setTrustManagerId(entity.getTrustManagerId());
            businessMainEntity.setCustomerCredit(entity.getCustomerCredit());
            businessMainEntity.setExistingDevice(entity.getExistingDevice());
            businessMainEntity.setCompetitorCondition(entity.getCompetitorCondition());
            businessMainEntity.setOtherCondition(entity.getOtherCondition());
            businessMainEntity.setBtype(0);
            rows = businessMainDao.update(businessMainEntity);
        }
        BusinessMainEntity mainEntity = (BusinessMainEntity) businessMainDao.getIBaseEntityById(entity.getId());
        if (entity.getAuditFlag() == 0) {
            //删除信审表数据
            businessTrustTrialDao.removeByCondition(" AND MAIN_ID=?", new String[]{entity.getId()});
            BusinessTrustTrialEntity trustTrialEntity = new BusinessTrustTrialEntity();
            //获取本公司的信控专员
            JSONObject credits = businessMainDao.getCreditManagerByUserId(entity.getCreateUserId());
            if (credits != null) {
                mainEntity.setTrustTrialId(credits.getString("id"));
                mainEntity.setTrustTrialName(credits.getString("name"));
                trustTrialEntity.setTrustTrialId(credits.getString("id"));
                trustTrialEntity.setTrustTrialName(credits.getString("roleName") + "-" + credits.getString("name"));
                if ("全款".equals(mainEntity.getBuyType())) {
                    mainEntity.setTrustTrialFlag(1);
                    trustTrialEntity.setTrustTrialFlag("1");
                } else {
                    mainEntity.setTrustTrialFlag(0);
                    trustTrialEntity.setTrustTrialFlag("0");
                }
                trustTrialEntity.setTrustTrialSort(1);
                trustTrialEntity.setMainId(entity.getId());
                mainEntity.setTrustManagerId(credits.getString("id"));
                businessTrustTrialDao.add(trustTrialEntity);
                JSONObject trusts = userDao.getViewByUserId(" AND main=1 AND roleName='信控总监' AND jobState!=1", new Object[]{}).get(0);
                trustTrialEntity.setTrustTrialId(trusts.getString("id"));
                trustTrialEntity.setTrustTrialName(trusts.getString("roleName") + "-" + trusts.getString("name"));
                trustTrialEntity.setTrustTrialSort(2);
                trustTrialEntity.setMainId(entity.getId());
                trustTrialEntity.setTrustTrialFlag("");
                businessTrustTrialDao.add(trustTrialEntity);
            } else {
                //获取信审人
                JSONObject trusts = userDao.getViewByUserId(" AND main=1 AND roleName='信控总监' AND jobState!=1", new Object[]{}).get(0);
                if (trusts != null) {
                    mainEntity.setTrustTrialId(trusts.getString("id"));
                    mainEntity.setTrustTrialName(trusts.getString("name"));
                    trustTrialEntity.setTrustTrialId(trusts.getString("id"));
                    trustTrialEntity.setTrustTrialName(trusts.getString("roleName") + "-" + trusts.getString("name"));
                    if ("全款".equals(mainEntity.getBuyType())) {
                        mainEntity.setTrustTrialFlag(1);
                        trustTrialEntity.setTrustTrialFlag("1");
                    } else {
                        mainEntity.setTrustTrialFlag(0);
                        trustTrialEntity.setTrustTrialFlag("0");
                    }
                    trustTrialEntity.setTrustTrialSort(1);
                    trustTrialEntity.setMainId(entity.getId());
                    mainEntity.setTrustManagerId(trusts.getString("id"));
                    businessTrustTrialDao.add(trustTrialEntity);
                }
            }
            businessMainDao.update(mainEntity);
        }
        //保存审核人信息
        //删除
        businessAuditDao.removeByCondition(" and MAIN_ID=?", new String[]{entity.getId()});
        //保存
        List<BusinessAuditEntity> auditEntityList = model.getAuditors();
        if (auditEntityList != null && auditEntityList.size() > 0) {
            for (int i = 0; i < auditEntityList.size(); i++) {
                if (StringUtils.isNotBlank(auditEntityList.get(i).getAuditorId())) {
                    if (entity.getAuditFlag() == 0 && i == 0) {
                        auditEntityList.get(i).setAuditFlag("0");
                    } else {
                        auditEntityList.get(i).setAuditFlag("-1");
                    }
                    auditEntityList.get(i).setMainId(entity.getId());
                    auditEntityList.get(i).setAuditSort(i);
                    auditEntityList.get(i).setAuditTime(null);
                    auditEntityList.get(i).setAuditAdvise("");
                    businessAuditDao.add(auditEntityList.get(i));
                }
            }
        }
        //保存抄送人信息
        businessCopierDao.removeByCondition(" and MAIN_ID=?", new String[]{entity.getId()});
        //添加
        List<BusinessCopierEntity> copierEntityList = model.getCopiers();
        for (int i = 0; i < copierEntityList.size(); i++) {
            copierEntityList.get(i).setMainId(entity.getId());
            businessCopierDao.add(copierEntityList.get(i));
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public Boolean delById(String id) {
        return businessMainDao.delById(id) > 0;
    }

    @Override
    public List<JSONObject> getBusinessList() {
        List<JSONObject> businessList =
                businessMainDao.getJSONListByCondition("AND DEL_FLAG = 0 ", new Object[]{});
        return businessList;
    }

    @Override
    public JSONObject getBusinessListByPage(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String customerName = jsonParams.getString("customerName");
        String modelName = jsonParams.getString("modelName");
        String createUserName = jsonParams.getString("createUserName");
        StringBuilder condition = new StringBuilder();
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        String userId = jsonParams.getString("userId");
        JSONObject users=userDao.getViewJSONById(userId);
        //StringBuffer condition = new StringBuffer();
        if ("信控总监".equals(users.getString("roleName"))
                ||"信控专员".equals(users.getString("roleName"))){
           condition.append(" and  buyType!='全款'");
        }
        if (StringUtils.isNotBlank(createUserName)) {
            condition.append(" and createUserName LIKE  '%" + createUserName + "%'");
        }
        if (StringUtils.isNotBlank(modelName)) {
            condition.append(" and modelName LIKE  '%" + modelName + "%'");
        }
        if (StringUtils.isNotBlank(customerName)) {
            condition.append(" and customerName LIKE  '%" + customerName + "%'");
        }
        //查询list
        List<JSONObject> records = businessMainDao.getJSONListByPage(userId, requestPage, pageSize,condition.toString());
        //查询总数
        Integer recordCount = businessMainDao.getJSONListByCount(userId,condition.toString());
        //分装前端需要的格式
        int pageCount = 0;
        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / pageSize + 1);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getBusinessById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        JSONObject result = businessMainDao.getJSONById(id);
        return result;
    }

    @Override
    public String getUnDoCount(String userId) {
        Integer count = 0;
        if (userId != null && !userId.isEmpty()) {
            count = businessMainDao.getUnDoCount(userId);
        }
        return count.toString();
    }

    @Override
    public JSONObject getById(String id) {
        BusinessEntity businessEntity = new BusinessEntity();
        businessEntity.setMain(JSON.toJavaObject(this.businessMainDao.getViewJSONById(id), BusinessMainEntity.class));
        businessEntity.setCopiers(this.businessCopierDao.getEntityListByCondition(" AND MAIN_ID = ? ", new Object[]{id}));
        businessEntity.setAuditors(this.businessAuditDao.getEntityListByCondition(" AND MAIN_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id}));
        businessEntity.setReceivers(this.receiverDao.getEntityListByCondition(" AND MAIN_ID =? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id}));
        businessEntity.setTrusts(this.businessTrustTrialDao.getEntityListByCondition(" AND MAIN_ID =?  ORDER BY TRUST_TRIAL_SORT ", new Object[]{id}));
        return (JSONObject) JSON.toJSON(businessEntity);
    }

    @Override
    public JSONObject getJSONByAuditAndCopier(String id) {
        JSONObject results = new JSONObject();
        JSONObject audit = new JSONObject();
        List<JSONObject> auditors = new ArrayList<>();
        List<JSONObject> copiers = new ArrayList<>();
        JSONObject usersView = userDao.getViewJSONListByCondition("AND id=? AND main=1", new Object[]{id}).get(0);
        //第一审核人为销售总监
        if (!"总经理".equals(usersView.getString("roleName"))) {
            if (!"销售总监".equals(usersView.getString("roleName"))) {
                JSONObject managers = businessMainDao.getManagerByUserId(id);
                if (managers != null) {
                    if (!StringUtils.isBlank(managers.getString("salesManager"))) {
                        audit.put("auditorId", managers.getString("saleId"));
                        audit.put("auditorName", managers.getString("salesManager"));
                        audit.put("roleName", managers.getString("roleName"));
                    }
                    auditors.add(audit);
                }
            }
            //第二审核人为总经理
            JSONObject topAudit = new JSONObject();
            JSONObject topManagers = businessMainDao.getTopManagerByUserId(id);
            if (topManagers != null) {
                if (!StringUtils.isBlank(topManagers.getString("salesManager"))) {
                    topAudit.put("auditorId", topManagers.getString("saleId"));
                    topAudit.put("auditorName", topManagers.getString("salesManager"));
                    topAudit.put("roleName", topManagers.getString("roleName"));
                }
                auditors.add(topAudit);
            }
        }
        //第三审核人为谈总
        JSONObject boss = userDao.getViewJSONById("2017121618514C22B68296F31AF8DDE2");
        JSONObject bossAudit = new JSONObject();
        bossAudit.put("auditorId", boss.getString("id"));
        bossAudit.put("auditorName", boss.getString("name"));
        bossAudit.put("roleName", boss.getString("roleName"));
        auditors.add(bossAudit);
        String noUserIds = "";
        for (int i = 0; i < auditors.size(); i++) {
            noUserIds += "'" + auditors.get(i).getString("auditorId") + "',";
        }
        noUserIds = noUserIds.substring(0, noUserIds.length() - 1);
        //查询抄送人
        //第一步 递归获取上级
        List<JSONObject> parentList = new ArrayList<>();
        userDao.getParentList(id, parentList);
        String userIds = "";
        for (int i = 0; i < parentList.size(); i++) {
            userIds += "'" + parentList.get(i).getString("id") + "',";
        }
        //第二步完成userIds= "'1','2','3','4','5','6','7','8'";
        StringBuffer sbCondition = new StringBuffer();
        sbCondition.append(" AND v_sys_part_time_for_report.userId NOT in(" + noUserIds + ")\n");
        List<JSONObject> userSupports = userDao.getSupportUserList(id, sbCondition.toString());
        if (userSupports != null && userSupports.size() > 0) {
            for (int i = 0; i < userSupports.size(); i++) {
                userIds += "'" + userSupports.get(i).getString("userId") + "',";
            }
        }
        userIds = userIds.substring(0, userIds.length() - 1);
        //获取查询到的人
        List<JSONObject> listUsers = userDao.getViewJSONListByCondition(" AND main=1  AND jobState !=1 AND id IN(" + userIds + ") " +
                " and id not IN (" + noUserIds + ") GROUP BY id ORDER BY companySortNo,departSortNo,roleSortNo,entryDate ", new Object[]{});
        for (int i = 0; i < listUsers.size(); i++) {
            JSONObject copier = new JSONObject();
            JSONObject users = listUsers.get(i);
            copier.put("copyPersonId", users.getString("id"));
            copier.put("copyPersonName", users.getString("name"));
            copiers.add(copier);
        }
        results.put("auditors", auditors);
        results.put("copiers", copiers);
        return results;
    }


    @Override
    public Boolean applyAudit(String jsonData) {
        JSONObject jsonObject = JSON.parseObject(jsonData);
        String id = jsonObject.getString("id");
        String userId = jsonObject.getString("userId");
        String userName = jsonObject.getString("userName");
        String auditFlag = jsonObject.getString("auditFlag");
        String advise = jsonObject.getString("advise");
        //保存历史审核原因信息
        BusinessReceiverEntity receiverEntity = new BusinessReceiverEntity();
        receiverEntity.setMainId(id);
        receiverEntity.setAuditId(userId);
        receiverEntity.setAuditName(userName);
        receiverEntity.setAuditFlag(auditFlag);
        receiverEntity.setAuditAdvise(advise);
        receiverEntity.setAuditType(1);
        receiverEntity.setAuditTime((businessAuditDao.getCurrentTime()));
        receiverDao.add(receiverEntity);
        //根据id获取主表信息
        BusinessMainEntity mainEntity = businessMainDao.getEntityById(id);
        UserEntity userEntity = userDao.getById(mainEntity.getCreateUserId());
        //根据id获取审核信息
        List<BusinessAuditEntity> auditEntityList = businessAuditDao.getEntityListByCondition(" AND MAIN_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id});
        BusinessAuditEntity auditEntityNow = null;
        for (int i = 0; i < auditEntityList.size(); i++) {
            if (auditEntityList.get(i).getAuditorId().equals(userId)) {
                //如果审核人==当前审核人
                auditEntityNow = auditEntityList.get(i);
                auditEntityNow.setAuditFlag(auditFlag);
                auditEntityNow.setAuditTime(businessAuditDao.getCurrentTime());
                auditEntityNow.setAuditAdvise(advise);
                businessAuditDao.update(auditEntityNow);

                //企业号:发消息通知申请人  (不发送给抄送人)
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", mainEntity.getCreateUserId());
                if ("2".equals(auditFlag)) {
                    //驳回
                    msgObject.put("content", String.format(BUSINESS_TRUST_REJECT,
                            userEntity.getName(),
                            mainEntity.getModelName(),
                            mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                            auditEntityNow.getAuditAdvise(),
                            auditEntityNow.getAuditorName(),
                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                }

                if ("1".equals(auditFlag)) {
                    if (i == auditEntityList.size() - 1) {
                        //如果是最后一个审核人
                        mainEntity.setAuditFlag(Integer.valueOf(auditFlag));
                        mainEntity.setCurrentAuditorId("");
                        mainEntity.setCurrentAuditorName("");
                        businessMainDao.update(mainEntity);
                        //企业号：审核通过之后信审人员接受消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", mainEntity.getTrustTrialId());
                        msgNextObject.put("content", String.format(BUSINESS_TRUST_AUDIT,
                                mainEntity.getTrustTrialName(),
                                mainEntity.getModelName(),
                                mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                                userEntity.getName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

                        //企业号: 最后一个审核通过,发送消息给申请人
                        //企业号: 最后一个审核通过,发送消息给申请人
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(BUSINESS_AUDIT_PASS,
                                userEntity.getName(),
                                mainEntity.getModelName(),
                                mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    } else {
                        BusinessAuditEntity auditEntityNext = auditEntityList.get(i + 1);
                        auditEntityNext.setAuditFlag("0");
                        businessAuditDao.update(auditEntityNext);

                        mainEntity.setCurrentAuditorId(auditEntityNext.getAuditorId());
                        String[] arrAuditorName = auditEntityNext.getAuditorName().split("-");
                        mainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                        businessMainDao.update(mainEntity);

                        //企业号: 审核通过,发送消息给申请人
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(BUSINESS_AUDIT_PASS,
                                userEntity.getName(),
                                mainEntity.getModelName(),
                                mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //企业号: 给下一审核人发消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", auditEntityNext.getAuditorId());
                        msgNextObject.put("content", String.format(BUSINESS_AUDIT_AUDIT,
                                auditEntityNext.getAuditorName(),
                                mainEntity.getModelName(),
                                mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                                userEntity.getName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

                        //推送: 给下一审核人推送红点提示
                        tokenDao.sendJPushMsg(auditEntityNext.getAuditorId(), String.format(BUSINESS_AUDIT_NOTIFY, mainEntity.getCreateUserName()));
                    }
                } else {
                    mainEntity.setAuditFlag(Integer.valueOf(auditFlag));
                    mainEntity.setCurrentAuditorId("");
                    mainEntity.setCurrentAuditorName("");
                    businessMainDao.update(mainEntity);
                }
                break;
            }
        }
        return true;
    }
/*
    @Autowired
    private BusinessAuditDao businessAuditDao;

    @Autowired
    private BusinessCopierDao businessCopierDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private DeviceBrandDao deviceBrandDao;
    @Autowired
    private DeviceModelDao deviceModelDao;
    @Autowired
    private Company2BrandDao company2BrandDao;


    @Override
    public String save(String jsonData) {
        BusinessEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), BusinessEntity.class);
        //第一步，保存主表信息
        BusinessMainEntity businessMainEntity = entity.getMain();
        businessMainEntity.setCreateTime(businessMainDao.getCurrentTime());
        businessMainEntity.setCurrentAuditorId("");
        businessMainEntity.setCurrentAuditorName("");

        if ("0".equals(businessMainEntity.getAuditFlag())) {
            //如果是提交申请，则设置当前审核人信息
            BusinessAuditEntity firstAuditor = entity.getAuditors().get(0);
            businessMainEntity.setCurrentAuditorId(firstAuditor.getAuditorId());
            String[] arrAuditorName = firstAuditor.getAuditorName().split("-");
            businessMainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);

            //企业号:给第一审核人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", firstAuditor.getAuditorId());
            msgObject.put("content", String.format(BUSINESS_AUDIT_AUDIT,
                    firstAuditor.getAuditorName(),
                    businessMainEntity.getProBrand() + " " + businessMainEntity.getProModel(),
                    businessMainEntity.getDealPrice() + "元 (" + businessMainEntity.getBuyType() + ")",
                    businessMainEntity.getCreateUserName(),
                    DateUtils.parse(businessMainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            //推送: 给第一审核人推送红点提示
            tokenDao.sendJPushMsg(firstAuditor.getAuditorId(), String.format(BUSINESS_AUDIT_NOTIFY, businessMainEntity.getCreateUserName()));
        }

        if (StringUtils.isBlank(businessMainEntity.getId()) || "0".equals(businessMainEntity.getId())) {
            //新建
            businessMainDao.add(businessMainEntity);
        } else {
            //编辑
            BusinessMainEntity oldMainEntity = businessMainDao.getEntityById(businessMainEntity.getId());
            oldMainEntity.setTitle(businessMainEntity.getTitle());
            oldMainEntity.setOrgName(businessMainEntity.getOrgName());
            oldMainEntity.setCreateUserId(businessMainEntity.getCreateUserId());
            oldMainEntity.setAuditFlag(businessMainEntity.getAuditFlag());
            oldMainEntity.setCreateUserName(businessMainEntity.getCreateUserName());
            oldMainEntity.setCurrentAuditorId(businessMainEntity.getCurrentAuditorId());
            oldMainEntity.setCurrentAuditorName(businessMainEntity.getCurrentAuditorName());

            oldMainEntity.setCusName(businessMainEntity.getCusName());
            oldMainEntity.setCusAddress(businessMainEntity.getCusAddress());
            oldMainEntity.setProBrand(businessMainEntity.getProBrand());
            oldMainEntity.setProModel(businessMainEntity.getProModel());
            oldMainEntity.setDealPrice(businessMainEntity.getDealPrice());
            oldMainEntity.setDealTime(businessMainEntity.getDealTime());
            oldMainEntity.setDealAddress(businessMainEntity.getDealAddress());
            oldMainEntity.setBuyType(businessMainEntity.getBuyType());
            oldMainEntity.setPayRatio(businessMainEntity.getPayRatio());
            oldMainEntity.setStageLimit(businessMainEntity.getStageLimit());
            oldMainEntity.setInterestFlag(businessMainEntity.getInterestFlag());
            oldMainEntity.setDisplaceFlag(businessMainEntity.getDisplaceFlag());
            oldMainEntity.setProOldBrandModel(businessMainEntity.getProOldBrandModel());
            oldMainEntity.setProOldYear(businessMainEntity.getProOldYear());
            oldMainEntity.setProOldPrice(businessMainEntity.getProOldPrice());
            oldMainEntity.setProOldHour(businessMainEntity.getProOldHour());
            oldMainEntity.setProOldReplacePrice(businessMainEntity.getProOldReplacePrice());
            oldMainEntity.setProOldAllowance(businessMainEntity.getProOldAllowance());
            oldMainEntity.setSaleAllowance(businessMainEntity.getSaleAllowance());
            oldMainEntity.setPartGift(businessMainEntity.getPartGift());
            oldMainEntity.setLaborFee(businessMainEntity.getLaborFee());
            oldMainEntity.setFreightFee(businessMainEntity.getFreightFee());
            oldMainEntity.setOtherBenefit(businessMainEntity.getOtherBenefit());
            oldMainEntity.setOtherBenefitPrice(businessMainEntity.getOtherBenefitPrice());
            oldMainEntity.setDealNetPrice(businessMainEntity.getDealNetPrice());
            oldMainEntity.setLimitPrice(businessMainEntity.getLimitPrice());
            oldMainEntity.setPartGiftDesc(businessMainEntity.getPartGiftDesc());
            oldMainEntity.setProBrandId(businessMainEntity.getProBrandId());
            oldMainEntity.setProModelId(businessMainEntity.getProModelId());
            businessMainDao.update(oldMainEntity);
        }

        String mainId = businessMainEntity.getId();

        //第二步，保存抄送人信息
        //删除
        businessCopierDao.removeByCondition(" AND FK_BUSINESS_ID = ? ", new String[]{mainId});
        //添加
        List<BusinessCopierEntity> businessCopierEntityList = entity.getCopiers();
        for (int i = 0; i < businessCopierEntityList.size(); i++) {
            businessCopierEntityList.get(i).setFkBusinessId(mainId);
            this.businessCopierDao.add(businessCopierEntityList.get(i));
        }

        //第三步，保存审核人信息
        //删除
        businessAuditDao.removeByCondition(" AND FK_BUSINESS_ID = ? ", new String[]{mainId});
        //添加
        List<BusinessAuditEntity> businessAuditEntityList = entity.getAuditors();
        if (businessAuditEntityList != null && businessAuditEntityList.size() > 0) {
            for (int i = 0; i < businessAuditEntityList.size(); i++) {
                if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(businessAuditEntityList.get(i).getAuditorId()) && !businessAuditEntityList.get(i).getAuditorId().equals("0")) {
                    if (businessMainEntity.getAuditFlag().equals("0") && i == 0) {
                        businessAuditEntityList.get(i).setAuditFlag("0");
                    } else {
                        businessAuditEntityList.get(i).setAuditFlag("-1");
                    }
                    businessAuditEntityList.get(i).setFkBusinessId(mainId);
                    businessAuditEntityList.get(i).setAuditSort(i);
                    businessAuditEntityList.get(i).setAuditTime(null);
                    businessAuditEntityList.get(i).setAuditAdvise("");
                    this.businessAuditDao.add(businessAuditEntityList.get(i));
                }
            }
        }

        return mainId;
    }


    @Override
    public String getUnDoCount(String userId) {
        Integer count = 0;
        if (userId != null && !userId.isEmpty()) {
            count = businessMainDao.getUnDoCount(userId);
        }
        return count.toString();
    }

    @Override
    public JSONObject getByPage(String userId, String key, String companyId, String auditFlag, String type, String createUserName, int requestPage, int pageSize) {
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (StringUtils.isNotEmpty(key)) {
            condition.append(" AND  TITLE LIKE '%" + key + "%' ");
        }
        if (StringUtils.isNotEmpty(auditFlag)) {
            condition.append(" AND AUDIT_FLAG = ?");
            sqlArgs.add(auditFlag);
        }
        if (StringUtils.isNotEmpty(createUserName)) {
            condition.append(" AND CREATE_USER_NAME LIKE  '%" + createUserName + "%'");
        }
        condition.append(" AND (CREATE_USER_ID = ? ");
        condition.append(" OR ( ");
        condition.append(" AUDIT_FLAG <> '-1' ");
        condition.append(" AND ( ");
        condition.append(" ID IN(SELECT FK_BUSINESS_ID FROM T_APL_BUSINESS_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
        condition.append(" OR ");
        //如果id是谈老板,抄送的不给他显示
        if ("2017121618514C22B68296F31AF8DDE2".equals(userId)) {
            condition.append(" ID IN(SELECT FK_BUSINESS_ID FROM T_APL_BUSINESS_COPIER LEFT JOIN T_APL_BUSINESS_MAIN ON T_APL_BUSINESS_COPIER.FK_BUSINESS_ID = T_APL_BUSINESS_MAIN.ID WHERE T_APL_BUSINESS_COPIER.COPY_PERSON_ID = ? AND( T_APL_BUSINESS_MAIN.AUDIT_FLAG = '2')");
            condition.append(" ) ");
        } else {
            condition.append(" ID IN(SELECT FK_BUSINESS_ID FROM T_APL_BUSINESS_COPIER WHERE COPY_PERSON_ID = ?) ");
        }
        condition.append(" ) ");
        condition.append(" ) ");
        condition.append(" ) ");
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);

        List<JSONObject> records = this.businessMainDao.getJSONListByPage(userId, condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        int recordCount = this.businessMainDao.getPageCount(condition.toString(), sqlArgs.toArray());
        int pageCount = 0;

        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            pageCount = (int) Math.ceil(recordCount / pageSize);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }


        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);

        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", records);
        objResult.put("pager", objPager);
        return objResult;
    }



    @Override
    public Boolean applyAudit(String id, String userId, String auditFlag, String advise) {
        //根据id获取主表信息
        BusinessMainEntity mainEntity = businessMainDao.getEntityById(id);
        //根据id获取审核信息
        List<BusinessAuditEntity> auditEntityList = businessAuditDao.getEntityListByCondition(" AND FK_BUSINESS_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id});
        BusinessAuditEntity auditEntityNow = null;
        for (int i = 0; i < auditEntityList.size(); i++) {
            if (auditEntityList.get(i).getAuditorId().equals(userId)) {
                //如果审核人==当前审核人
                auditEntityNow = auditEntityList.get(i);
                auditEntityNow.setAuditFlag(auditFlag);
                auditEntityNow.setAuditTime(businessAuditDao.getCurrentTime());
                auditEntityNow.setAuditAdvise(advise);
                businessAuditDao.update(auditEntityNow);

//                //企业号:发消息通知申请人  (不发送给抄送人)
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", mainEntity.getCreateUserId());
                if ("2".equals(auditFlag)) {
                    //驳回
                    msgObject.put("content", String.format(BUSINESS_AUDIT_REJECT,
                            mainEntity.getCreateUserName(),
                            mainEntity.getProBrand() + " " + mainEntity.getProModel(),
                            mainEntity.getDealPrice() + "元 (" + mainEntity.getBuyType() + ")",
                            auditEntityNow.getAuditAdvise(),
                            auditEntityNow.getAuditorName(),
                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                }

                if ("1".equals(auditFlag)) {
                    if (i == auditEntityList.size() - 1) {
                        //如果是最后一个审核人
                        mainEntity.setAuditFlag(auditFlag);
                        mainEntity.setCurrentAuditorId("");
                        mainEntity.setCurrentAuditorName("");
                        businessMainDao.update(mainEntity);

                        //企业号: 最后一个审核通过,发送消息给申请人
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(BUSINESS_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getProBrand() + " " + mainEntity.getProModel(),
                                mainEntity.getDealPrice() + "元 (" + mainEntity.getBuyType() + ")",
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    } else {
                        BusinessAuditEntity auditEntityNext = auditEntityList.get(i + 1);
                        auditEntityNext.setAuditFlag("0");
                        businessAuditDao.update(auditEntityNext);

                        mainEntity.setCurrentAuditorId(auditEntityNext.getAuditorId());
                        String[] arrAuditorName = auditEntityNext.getAuditorName().split("-");
                        mainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                        businessMainDao.update(mainEntity);

                        //企业号: 审核通过,发送消息给申请人
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(BUSINESS_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getProBrand() + " " + mainEntity.getProModel(),
                                mainEntity.getDealPrice() + "元 (" + mainEntity.getBuyType() + ")",
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //企业号: 给下一审核人发消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", auditEntityNext.getAuditorId());
                        msgNextObject.put("content", String.format(BUSINESS_AUDIT_AUDIT,
                                auditEntityNext.getAuditorName(),
                                mainEntity.getProBrand() + " " + mainEntity.getProModel(),
                                mainEntity.getDealPrice() + "元 (" + mainEntity.getBuyType() + ")",
                                mainEntity.getCreateUserName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

                        //推送: 给下一审核人推送红点提示
                        tokenDao.sendJPushMsg(auditEntityNext.getAuditorId(), String.format(BUSINESS_AUDIT_NOTIFY, mainEntity.getCreateUserName()));
                    }
                } else {
                    mainEntity.setAuditFlag(auditFlag);
                    mainEntity.setCurrentAuditorId("");
                    mainEntity.setCurrentAuditorName("");
                    businessMainDao.update(mainEntity);
                }
                break;
            }
        }
        return true;
    }

    @Override
    public Boolean removeById(String id) {
        return businessMainDao.removeById(id) > 0;
    }

    @Override
    public Boolean copierReturn(String id, String copierReturnReason) {
        boolean success = businessMainDao.copierReturn(id, copierReturnReason) > 0;
        if (success) {
            //企业号 抄送人驳回
            BusinessMainEntity mainEntity = businessMainDao.getEntityById(id);
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", mainEntity.getCreateUserId());
            msgObject.put("content", String.format(BUSINESS_COPIER_REJECT,
                    mainEntity.getCreateUserName(),
                    mainEntity.getProBrand() + " " + mainEntity.getProModel(),
                    mainEntity.getDealPrice() + "元 (" + mainEntity.getBuyType() + ")",
                    mainEntity.getCopierReturnReason()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        return success;
    }

    @Override
    public List<JSONObject> getBrandByCompanyId(String companyId) {
        return deviceBrandDao.getBrandByCompanyId(companyId);
    }

    @Override
    public List<JSONObject> getModelByBrandId(String brandId) {
        return deviceModelDao.getModelByBrandId(brandId);
    }
    */


}
